package com.ewanghuiju.app.widget;

import android.text.TextUtils;

import com.ewanghuiju.app.base.BaseView;
import com.ewanghuiju.app.model.http.exception.ApiException;
import com.ewanghuiju.app.util.LogUtil;

import java.net.UnknownHostException;

import io.reactivex.subscribers.ResourceSubscriber;
import retrofit2.HttpException;

/**
 * @author sj  qq:751943509
 * @class describe
 * @time 2020/2/14
 */
public abstract class CommonSubscriber<T> extends ResourceSubscriber<T> {
    private BaseView mView;
    private String mErrorMsg;
    private boolean isShowErrorState = true;
    private boolean isShowToast = true;

    protected CommonSubscriber(BaseView view) {
        this.mView = view;
    }

    protected CommonSubscriber(BaseView view, String errorMsg) {
        this.mView = view;
        this.mErrorMsg = errorMsg;
    }

    protected CommonSubscriber(BaseView view, boolean isShowErrorState) {
        this.mView = view;
        this.isShowErrorState = isShowErrorState;
    }

    protected CommonSubscriber(BaseView view, boolean isShowErrorState, boolean isShowToast) {
        this.mView = view;
        this.isShowErrorState = isShowErrorState;
        this.isShowToast = isShowToast;
    }

    protected CommonSubscriber(BaseView view, String errorMsg, boolean isShowErrorState) {
        this.mView = view;
        this.mErrorMsg = errorMsg;
        this.isShowErrorState = isShowErrorState;
    }

    @Override
    public void onComplete() {
    }

    @Override
    public void onError(Throwable e) {
        if (mView == null) {
            return;
        }
        if (mErrorMsg != null && !TextUtils.isEmpty(mErrorMsg)) {
            mView.showErrorMsg(mErrorMsg, isShowToast);
        } else if (e instanceof ApiException) {
            mView.showErrorMsg(e.getMessage(), isShowToast);
        } else if (e instanceof HttpException) {
            mView.showErrorMsg("网络加载失败", isShowToast);
        } else if (e instanceof UnknownHostException) {
            mView.showErrorMsg("网络加载失败", isShowToast);
        } else {
            mView.showErrorMsg("请求出错", isShowToast);
        }
        if (isShowErrorState) {
            mView.stateError();
        }
    }
}
